﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Microsoft.Practices.Unity;

namespace BootCms.Environment
{
    public class PerHostLifetimeManager : SynchronizedLifetimeManager 
    { 
        private readonly Func<HttpContextBase> context; 
        private readonly IDictionary<string, object> store; 

        public PerHostLifetimeManager(Func<HttpContextBase> context) 
        { 
            this.context = context; 
            store = new Dictionary<string, object>(); 
        } 
        
        protected override object SynchronizedGetValue() 
        { 
            var host = GetHost(); 
            if (!store.ContainsKey(host))             
                return null; 
            return store[host]; 
        } 
        
        protected override void SynchronizedSetValue(object newValue) 
        { 
            store[GetHost()] = newValue; 
        } 
        
        private string GetHost() 
        {
            return context().Request.Headers["Host"]; 
        } 
    }
}